//
//  FamilyViewController.m
//  leo
//
//  Created by 常艳 on 15/9/17.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "FamilyViewController.h"
#import "DateViewController.h"
#import "ScanViewController.h"
#import "DataManager.h"
#import "SyncManager.h"
#import "BindViewController.h"
#import "AppDelegate.h"
@interface FamilyViewController ()
@property(nonatomic,strong) DataManager *dataManager;
@property(nonatomic,strong) SyncManager *syncManager;
@property(nonatomic,strong) Manager *manager;
@property(nonatomic,strong) NSString *photoUrl;
@property(nonatomic,strong) NSString *photoName;
@property(strong,nonatomic) NSString *uid;
@property(nonatomic,assign) int groupId;
@property(nonatomic,strong) UIActionSheet *actionSheet;
@property(nonatomic,strong) UIImagePickerController *picker;
@property(nonatomic,strong) NSString *nickName;
@end

@implementation FamilyViewController
-(void)dealloc
{
    self.actionSheet.delegate=nil;
    self.actionSheet=nil;
    self.picker.delegate=nil;
    self.picker=nil;
    self.dataManager=NULL;
    self.syncManager=NULL;
    self.manager=NULL;
    self.photoUrl=NULL;
    self.photoName=NULL;
    self.uid=NULL;
    self.nickName=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.extendedLayoutIncludesOpaqueBars=YES;
    self.title=@"完善账号信息";
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Back_icon@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    [self.navigationItem setLeftBarButtonItem:leftButton];
    [self.headImg.layer setMasksToBounds:YES];
    self.headImg.layer.cornerRadius= self.headImg.bounds.size.width/2;
    self.headImg.clipsToBounds=YES;
    [self.indicaorView.layer setMasksToBounds:YES];
    self.indicaorView.layer.cornerRadius=5;
    self.dataManager=[[DataManager alloc] init];
    if(self.dataManager==NULL)
    {
        NSLog(@"%@,viewDidLoad,dataManager is null",faimly_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 19"];
        return;
    }
    self.syncManager=[[SyncManager alloc] init];
    if(self.syncManager==NULL)
    {
        NSLog(@"%@,viewDidLoad,syncManager is null",faimly_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 20"];
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,viewDidLoad,user is null",faimly_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 21"];
        return;
    }
    self.uid=user.uid;
    if(self.uid==NULL)
    {
        NSLog(@"%@,viewDidLoad,uid is null",faimly_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 22"];
        return;
    }
    if(user.nickName!=NULL&&![user.nickName isEqualToString:@"(null)"]&&![user.nickName isEqualToString:@""])
    {
        self.nickLabel.text=user.nickName;
        self.nickName=user.nickName;
    }
    if(user.account!=NULL&&![user.account isEqualToString:@"(null)"]&&![user.account isEqualToString:@""])
    {
        self.accountLabel.text=user.account;
    }
    self.actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:nil
                                  delegate:self
                                  cancelButtonTitle:nil
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"拍照", @"从手机相册选择",@"取消",nil];
    self.actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    self.picker = [[UIImagePickerController alloc] init];
    self.picker.delegate = self;
    //设置选择后的图片可被编辑
    self.picker.allowsEditing = YES;
    //设置图片选择器样式
    self.picker.allowsEditing = YES;
    
    self.picker.navigationBar.translucent =NO;
    
    [self.picker.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    [self.picker.navigationBar setBarTintColor:[UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1.0]];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (IBAction)setImg:(id)sender {

    [self.actionSheet showInView:self.view];

}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self camera];
    }else if (buttonIndex == 1) {
        [self LocalPhoto];      
    }else if(buttonIndex == 2) {
        
    }
    
}

- (IBAction)setBirth:(id)sender {
    
    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIWindow *alertView=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //
    DateViewController *date=[[DateViewController alloc]init];
    //
    [date setMotherWindow:alertView];
    [date setMotherLabel:self.birthLabel];
    if(self.birthLabel.text!=NULL&&![self.birthLabel.text isEqualToString:@"请选择"])
    {
        [date setOriginalBirth:self.birthLabel.text];
    }
    else
    {
        [date setOriginalBirth:NULL];
    }
    alertView.rootViewController=date;
    [keyWindow addSubview:alertView];
    [alertView setWindowLevel:UIWindowLevelAlert];
    [alertView makeKeyAndVisible];
}
-(void)LocalPhoto
{
    self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //[[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    [self presentViewController:self.picker animated:YES completion:nil];
}
-(void)camera
{
    self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //[[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    [self presentViewController:self.picker animated:YES completion:nil];
}
//取消选择
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        NSData *data=UIImageJPEGRepresentation(image, 0.3);
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [[Tooler getDocumentDirectory] stringByAppendingString:@"/headimg"];
        if([Tooler isDirectoryExist:DocumentsPath])
        {
            NSString *ts=[Tooler getTS];
            self.photoName=[NSString stringWithFormat:@"/headimg/image%@.jpg",ts];
            //得到选择后沙盒中图片的完整路径
            self.photoUrl = [[NSString alloc]initWithFormat:@"%@/image%@.jpg",DocumentsPath,ts];
            NSError *error;
            [data writeToFile:self.photoUrl options:NSDataWritingFileProtectionComplete error:&error];
            if(error==NULL)
            {
                self.headImg.image=[UIImage imageNamed:self.photoUrl];
            }
            
        }
        [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
        [self.picker dismissViewControllerAnimated:YES completion:nil];
   
    }
    
}
- (IBAction)setNick:(id)sender {
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"请输入昵称"
                                                    message:nil
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"确定", nil];
    // 基本输入框，显示实际输入的内容
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    //设置输入框的键盘类型
    UITextField *nickTextField = [alert textFieldAtIndex:0];
    nickTextField.keyboardType = UIKeyboardTypeDefault;
    [nickTextField addTarget:self action:@selector(nickTextFieldChange:) forControlEvents:UIControlEventEditingChanged];
    if(self.nickName!=NULL&&![self.nickName isEqualToString:@"(null)"]&&![self.nickName isEqualToString:@""])
    {
        nickTextField.text=self.nickName;
    }
    [alert show];
    alert=NULL;
    
}
- (void)nickTextFieldChange:(UITextField *)textField
{
        if (textField.text.length > 20) {
            textField.text = [textField.text substringToIndex:20];
        }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // 取得输入的值
    UITextField *nickTextField = [alertView textFieldAtIndex:0];
    NSString* nickName = [nickTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if([nickName isEqualToString:@""]||[nickName length]<=0)
    {
        [self showErrorMsg:@"昵称不能为空"];
    }
    else if([Tooler checkStringIllegal:nickName ChnLength:6 EngLength:10]==1)
    {
        [self showErrorMsg:@"昵称不合法"];
    }
    else if([Tooler checkStringIllegal:nickName ChnLength:6 EngLength:10]==2)
    {
        [self showErrorMsg:@"昵称太长，中文字符只能输入6个，英文字符最多10个"];
    }
    else
    {
        self.nickLabel.text=nickName;
        self.nickName=nickName;
    }
}

- (IBAction)next:(id)sender {
    self.nextBtn.enabled=NO;
    self.indicaorView.hidden=NO;
    self.indicator.hidden=NO;
    [self.indicator startAnimating];
    //更新设置用户信息
    [self setUserInfo];
    
}
-(void)setUserInfo
{
    User *user=[User sharedSingleton];
    user.birth=self.birthLabel.text;
    NSString *birth=[NSString stringWithFormat:@"%@ 00:00:00",user.birth];
    NSString *birthStamp=[Tooler strToLocalTime:birth];
    if(self.nickLabel.text!=NULL&&[self.nickLabel.text length]>0)
        user.nickName=self.nickLabel.text;
    user.birth=birthStamp;
    user.pic_url=self.photoName;
    user.photoName=self.photoName;
    user.full_url=self.photoUrl;
    user.email=@"315261347@qq.com";
    user.address=@"china";
    user.age=30;
    if(self.groupId>0&&!(self.manager.groupId>0))
    {
        self.manager.groupId=self.groupId;
    }
    if([self.deviceUid intValue]>0)
    {
        self.manager.deviceUid=self.deviceUid;
    }
    
    [self.syncManager setUserInfo:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        self.nextBtn.enabled=YES;
        if(result==SUCESS)
        {
            self.indicaorView.hidden=YES;
            self.indicator.hidden=YES;
            [self.indicator stopAnimating];
            ScanViewController *scanController=[[ScanViewController alloc] init];
            scanController.type=3;
            UINavigationController *scanNav=[[UINavigationController alloc] initWithRootViewController:scanController];
            AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
            if(mydelegate!=NULL)
                [mydelegate setNavProperty:scanNav];
            self.view.window.rootViewController=scanNav;
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        else
        {
            [Tooler showHttpMsg:result description:description msg:@"设置用户信息失败"];
        }

    }];
    
}
-(void)showErrorMsg:(NSString *)msg
{
    self.nextBtn.enabled=YES;
    self.indicaorView.hidden=YES;
    self.indicator.hidden=YES;
    [self.indicator stopAnimating];
    [LeoMsg showMsg:msg];
}
-(void)backAction
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    BindViewController *bindView=[[BindViewController alloc] init];
    UINavigationController *bindNavigationController = [[UINavigationController alloc] initWithRootViewController:bindView];
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate!=NULL)
        [mydelegate setNavProperty:bindNavigationController];
    self.view.window.rootViewController=bindNavigationController;
    bindView=NULL;

}
@end
